package com.chenjiagou.bookingdemo.service;

import com.chenjiagou.bookingdemo.entity.Booking;
import com.chenjiagou.bookingdemo.entity.BookingWithUsername;
import com.chenjiagou.bookingdemo.mapper.BookingMapper;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class BookingService {

    private final BookingMapper bookingMapper;

    public BookingService(BookingMapper bookingMapper) {
        this.bookingMapper = bookingMapper;
    }

    // 1. 查看所有订单
    public List<BookingWithUsername> getAllBookings() {
        return bookingMapper.getAllBookingsWithUsername();
    }

    // 2. 按ID查看订单
    public Optional<Booking> getBookingById(Long id) {
        return bookingMapper.getBookingById(id);
    }

    // 3. 更改订单（需校验状态合理性，例如：已取消订单不能修改）
    public Booking updateBooking(Booking updatedBooking) {
        // 校验：若订单已取消，拒绝修改
        Optional<Booking> existingBooking = bookingMapper.getBookingById(updatedBooking.getId());
        if (existingBooking.isPresent()) {
            Booking booking = existingBooking.get();
            if (booking.getStatus() == 4) { // 4=已取消
                throw new RuntimeException("已取消订单无法修改");
            }
            // 允许修改的字段（根据需求调整）
            booking.setBooking_no(updatedBooking.getBooking_no());
            booking.setUser_id(updatedBooking.getUser_id());
            booking.setFlight_id(updatedBooking.getFlight_id());
            booking.setSeat_class_id(updatedBooking.getSeat_class_id());
            booking.setStatus(updatedBooking.getStatus());
            booking.setTotal_amount(updatedBooking.getTotal_amount());
            booking.setDeposit_paid(updatedBooking.getDeposit_paid());
            booking.setExpire_time(updatedBooking.getExpire_time());
            int rowsAffected = bookingMapper.updateBooking(booking);
            if (rowsAffected > 0) {
                return booking;
            }
        }
        throw new RuntimeException("订单不存在或更新失败");
    }

    // 4. 退订订单（修改状态为"4-取消"）
    public void cancelBooking(Long id) {
        int rowsAffected = bookingMapper.cancelBooking(id);
        if (rowsAffected == 0) {
            throw new RuntimeException("订单取消失败，可能订单不存在");
        }
    }

    public List<BookingWithUsername> findBookingsByUsername(String username) {
        return bookingMapper.findBookingsByUsername(username);
    }

    public Optional<BookingWithUsername> getBookingDetailById(Long id) {
        return bookingMapper.getBookingDetailById(id);
    }

    // 按状态查询订单
    public List<BookingWithUsername> getBookingsByStatus(byte status) {
        return bookingMapper.getBookingsByStatus(status);
    }

    // 查询非指定状态的订单
    public List<BookingWithUsername> getBookingsByStatusNot(byte status) {
        return bookingMapper.getBookingsByStatusNot(status);
    }
}